const request = require('request');
const fs = require('fs');


Date.prototype.format = function (fmt) { //author: meizz   
  var o = {
    "M+": this.getMonth() + 1,                 //月份   
    "d+": this.getDate(),                    //日   
    "h+": this.getHours(),                   //小时   
    "m+": this.getMinutes(),                 //分   
    "s+": this.getSeconds(),                 //秒   
    "q+": Math.floor((this.getMonth() + 3) / 3), //季度   
    "S": this.getMilliseconds()             //毫秒   
  };
  if (/(y+)/.test(fmt))
    fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
  for (var k in o)
    if (new RegExp("(" + k + ")").test(fmt))
      fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
  return fmt;
}

function promiseRequest(json) {

  const options = {
    url: 'http://api.waditu.com',
    method: 'POST',
    json: json
  };

  return new Promise(function (resolve, reject) {
    request(options, function (err, res, body) {
      if (err) {
        return reject(err);
      } else if (res.statusCode !== 200) {
        err = new Error("Unexpected status code: " + res.statusCode);
        err.res = res;
        return reject(err);
      }
      resolve(body);
    });
  });
}


function writeFile(json, filePath) {
  try {
    // fs.writeFile(filePath, JSON.stringify(json, null, 4),
    //   function (err) {
    //     if (err) {
    //       console.log(filePath + "文件写入失败")
    //     } else {
    //       console.log(filePath + "文件写入成功");
    //     }
    //   })
    fs.writeFileSync(filePath, JSON.stringify(json, null, 4))
    console.log(filePath + "文件写入成功");
  } catch (e) {
    console.log(e);
  }
}



; (async () => {

  // 交易日历
  let dest = {
    "api_name": "trade_cal",
    "token": "0affa53db2b6d3ec6b09ff30fde78f232dc168336a05767f7fa98a63",
    "params": { "exchange": 'SSE', "start_date": '20190101', "end_date": '20191201' },
    "fields": "cal_date,is_open"
  }

  var body = await promiseRequest(dest)
  if (body.code == 0) {
    // console.dir(body.data.items)
    writeFile(body.data.items, 'trade_cal.json')
  }


  // 基础信息数据
  dest = {
    "api_name": "stock_basic",
    "token": "0affa53db2b6d3ec6b09ff30fde78f232dc168336a05767f7fa98a63",
    "params": {},
    "fields": "ts_code,symbol,name,market"
  }

  var body = await promiseRequest(dest)
  if (body.code == 0) {
    // console.dir(body.data.items)
    writeFile(body.data.items, 'stock_basic.json')
  }

 

})()
